package leetcode13;

import java.util.*;
/**
 * 347. 前 K 个高频元素
 */
public class test71 {
    /**
     * 使用优先队列
     * @param nums
     * @param k
     * @return
     */
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i = 0;i < nums.length;i++){
            map.put(nums[i],map.getOrDefault(nums[i],0) + 1);
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>(k,(a,b)->map.get(a) - map.get(b));
        for(int key:map.keySet()){
            if(queue.size() < k){
                queue.offer(key);
            }else{
                if(map.get(key) > map.get(queue.peek())){
                    queue.poll();
                    queue.offer(key);
                }
            }
        }
        int[] res = new int[k];
        int index = 0;
        while(!queue.isEmpty()){
            res[index] = queue.poll();
            index++;
        }
        return res;
    }
}
